//
//  SawtoothGenerator.m
//  CocoaSynth
//
//  Created by Pierre DUCHENE on 17/02/10.
//  Copyright 2010 Pierre DUCHENE. All rights reserved.
//

//
//  SinusoidGenerator.m
//  CocoaSynth
//
//  Created by Pierre DUCHENE on 09/02/10.
//  Copyright 2010 Pierre DUCHENE. All rights reserved.
//

#import "SawtoothGenerator.h"
#import "SampleProtocol.h"
#import "Sample.h"
#import "System.h"

@implementation SawtoothGenerator

#pragma mark -
#pragma mark Accessors

@synthesize module;

#pragma mark -
#pragma mark Memory Management

- (id)init
{
	if (self = [super init]) {
		module = nil;
	}
	return self;
}

- (void)dealloc
{
	[module release];
	module = nil;
	
	[super dealloc];
}

#pragma mark -
#pragma mark ComputingStrategyProtocol

- (id<SampleProtocol>)execute
{
	id<SampleProtocol> result = [[Sample alloc] init];
	
	// Get system infos
	System* system = [System sharedSystem];
	NSUInteger sampleSize = [system sampleSize];
	double sampleIndex = [system samplePosition];
	double sampleRate = [system sampleRate];
	
	// Get module infos
	float f_0 = [module baseFrequency];
	float k = [module exponentialFrequency];
	NSArray* fm = [[module inputSample] voltages];
	
	NSMutableArray* tempResult = [[NSMutableArray alloc] init];
	float Vfm;
	float f;
	float cycleLength;
	for (int i = 0; i < sampleSize; i++) {
		// Compute outputfrequency
		Vfm = [[fm objectAtIndex:i] floatValue];
		f = f_0 * pow(2, (k + Vfm)); // f = f0 * 2^(k+Vfm)
		// Generate a simple sinusoid
		cycleLength = sampleRate / f;
		float t_a = sampleIndex/cycleLength;
		float newValue = 2 * (t_a - floor(t_a + 0.5));
		//float newValue = sin( sampleIndex / cycleLength * two_pi) * kDefaultAmplitude;
		[tempResult insertObject:[NSNumber numberWithFloat:newValue] atIndex:i];
		
		sampleIndex += 1.0;
		if (sampleIndex > cycleLength)
			sampleIndex -= cycleLength;
	}
	[system setSamplePosition:sampleIndex];
	[result setVoltages:[NSArray arrayWithArray:tempResult]];
	[tempResult release];
	return [result autorelease];
}


@end
